<?php

namespace App\Http\Controllers\Web\Member\Seller;

use App\Http\Controllers\Web\BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class ProductController extends BaseController
{
    protected $api_url = [
        'index' => ['get', 'seller/product'],
        'show' => ['get', 'seller/product/%d'],
        'store' => ['post', 'seller/product'],
        'update' => ['post', 'seller/product/%d'],
        'put' => ['put', ''],
        'delete' => ['delete', ''],
        'cupboards'=>['get','seller/product/cupboards'],
        'batchdel'=>['post','seller/product/batchdel'],
        'batchsale'=>['post','seller/product/batchsale'],
        
        'default_account'=>['get', 'seller/ejbao/default_account'],
        
        'brand_index' => ['get', 'brand'],
        'cate_index'=> ['get', 'cate'],
        'attr_index'=> ['get', 'attr'],
        
        'attr_val_store' => ['post', 'seller/attrval'],
        'attr_val_del' => ['delete', 'seller/attrval/%d'],
        
        'pattrs'=> ['get', 'pattrs/attr/%d'],
        
        'categories' => ['get', 'shop/categories/%d'],
    ];

    protected $shop_id;
    protected $user_id;
    protected $request;

    public function __construct(Request $request)
    {
        
        $this->request = $request;
    }

    public function index()
    {
        
        //参数部分
        $search_params = $this->request->all(['goods_name','goods_id','company_name','is_for_sale','status','updated_at','created_at','product_type','price']);
        
        if(!isset($search_params['product_type']  )){
            $search_params['product_type'] = 1;
        }
        
        if(isset($search_params['is_for_sale']  ) && $search_params['is_for_sale'] == 2){
            $search_params['status'] = 0;
            unset($search_params['is_for_sale']);
        }
        
        $page = $this->request->get('page', 1);
        $params = [
            'search' => search_params($search_params),
            'searchJoin' => 'and',
            'page' => $page,
            'orderBy'=>'id',
            'sortedBy'=>'desc',
            //'with' => 'skus',
        ];

        //请求部分
        $ret = http_web($this->api_url['index'])->send($params);
        //结果处理部分
        $data = paginate($this->request, $ret['data']);
         
        //回填搜索框值
        $data['search_params'] = $search_params;
        session(['current_page'=>isset($data['page']['current_page']) ? $data['page']['current_page']:1]);
        
        return view('web.user.seller.product', $data);
    }
    
    public function create()
    {
        $this->shop_id = session('user_shop_id');
        $this->user_id = session('user_id');
        $data = $this->request->all(['step','cname','categories']);
        $id =$this->request->get('id','');
        $cats =$this->request->get('categories','');
        
        $data['c1'] = $data['c2'] = $data['c3'] = "";
        $data['first_cat'] = $data['second_cat'] = $data['third_cat'] =0;
        
        if(isset($data['cname'])){
            $cname= explode(",",$data['cname']);
            $data['c1'] = isset($cname[0]) ? $cname[0] : "'";
            $data['c2'] = isset($cname[1]) ? $cname[1] : "'";
            $data['c3'] = isset($cname[2]) ? $cname[2] : "'";
        }
        
        if(isset($data['categories'])){
            $cids= explode(",",$data['categories']);
            $data['first_cat'] = isset($cids[0]) ? $cids[0] :  0;
            $data['second_cat'] = isset($cids[1]) ? $cids[1] :  0;
            $data['third_cat'] = isset($cids[2]) ? $cids[2] :  0;
            $data['cate_type'] = isset($cids[3]) ? $cids[3] :  1;
        }
        


        $has_default = false;
        if(Redis::exists('has_default_'.$this->user_id)){
            $has_default = Redis::get('has_default_'.$this->user_id);
        }else{
            $ret = http_web($this->api_url['default_account'])->send();
            
            if( isset($ret['code']) && $ret['code']===0 && isset($ret['data'][0])){
                 Redis::set('has_default_'.$this->user_id,true);
                $has_default = true;
            } 
        }
        
        if(!$has_default){
            return  redirect("/member/seller/account");
        } 
         
        if($data['step'] == 'detail'){
            if($id){
                return redirect("/member/seller/product/{$id}/edit?cats={$cats}");
            }
  
            $categories = http_web($this->api_url['categories'],[$this->shop_id])->send();
            $data['categories'] = [];
            if(isset($categories['data'][0])){
                $data['categories']=$categories['data'];
            }
           
//             $params = [
//                 'type' => 'all',
//             ];
            
//             $brands = http_web($this->api_url['brand_index'])->send($params);
            
//             $data['brands'] = [];
//             if(isset($brands['code']) && $brands['code'] === 0 ){
//                 $data['brands'] = $brands['data']['list'];
//             }
            
            $data['brands'] = [];
            if(Redis::exists('brand')){
                $brands  = Redis::hgetall('brand');
                foreach($brands as $b){
                    $data['brands'][] = json_decode($b,true);
                }
            }else{
                $params = [
                    'type' => 'all',
                ];
                
                $brands = http_web($this->api_url['brand_index'])->send($params);
                
                
                if(isset($brands['code']) && $brands['code'] === 0 ){
                    $data['brands'] = $brands['data']['list'];
                    foreach($brands['data']['list'] as $bl){
                        Redis::hset('brand',$bl['id'],json_encode($bl));
                    }
                }
            }
            
            $params['search']=search_params(['is_sku'=>1]);
            $params['with']='attrValues';
 
            $cate = [];
            $data['attrs']  = [];
            //这里只负责取 存的话有添加分类时候自身会存
            if(Redis::exists("categorys")){
                $cate = Redis::hget("categorys",$data['third_cat']);
                if($cate){
                    $cate = json_decode($cate,true);
                    $data['attrs']  = json_decode($cate['attrs'],true);
                }
             
            }
            
            if(!$cate){
                $params = [
                    'search' => search_params(['id'=>$data['third_cat']]),
                ];
                $cates =  http_web($this->api_url['cate_index'])->send($params);
                
                if(isset($cates['code']) && $cates['code'] === 0 ){
                    if(isset($cates['data']['list'][0])){
                        $data['attrs']  = json_decode($cates['data']['list'][0]['attrs'],true);
                    }
                }
            }
    
            
            $cupboards = http_web($this->api_url['cupboards'])->send(['shop_id'=>$this->shop_id,'product_type'=>$data['cate_type']]);
            if(isset($cupboards['data'])){
                $data['cupboards'] = $cupboards['data'];
            }else{
                $data['cupboards'] = 0;
            }
            
            $data['request_url']=route('product.store');
            
            if(!isset($data['is_cupboard']) || !$data['is_cupboard']){
                $data['is_cupboard'] = 0;
            }
            $old_data = app('request')->session()->get('_old_input');
            if(is_array($old_data)){
                unset($old_data['skus']);
                $data = array_merge($data,$old_data);
            }
            old_set($data);
          
            if($data['cate_type'] == 1){
                return view('web.user.seller.product_add_detail', $data);
            }else{
                return view('web.user.seller.product_add_detail_zz', $data);
            }
            
            
        }else{
            $cates = [];
            $data['cates'] = [];
            //
            if(Redis::exists("categorys")){
                $cateall = Redis::hgetall("categorys");
                if(is_array($cateall)){
                    foreach($cateall as $c){
                        $cates[] = json_decode($c,true);
                    }
                    $cates = sortArrByManyField( $cates,'root_id',SORT_ASC,'pid',SORT_ASC,'sort',SORT_ASC,'id',SORT_ASC);
                    foreach($cates as $c){
                        if($c['pid'] == 0){
                            $data['cates'][] =$c;
                        }
                    }
                }
            }
            //
            
            if(!$data['cates']){
                $params = [
                    'type' => 'all',
                    'search' => search_params(['pid'=>0]),
                ];
                $cates =  http_web($this->api_url['cate_index'])->send($params);
                
                
                if(isset($cates['code']) && $cates['code'] === 0 ){
                    $data['cates'] = $cates['data']['list'];
                }
            }
            $data['id'] = $id;
            old_set($data);
            return view('web.user.seller.product_add_cate', $data);
        }
        
    }
    
    public function store(Request $request){
        //验证部分
        $data = $this->form();
        $this->shop_id = session('user_shop_id');
        $this->user_id = session('user_id');
        
        $data['shop_id'] = $this->shop_id;
        $data['user_id'] = $this->user_id;
        if(isset($data['images'])){
            $data['images'] = json_encode($data['images']);
        }
        
        //$data['name'] = $data['product_desc'];
        
        $data['pattrs'] = "";
        if(isset($data['product_attrs']) && is_array($data['product_attrs'])){
            foreach($data['product_attrs'] as $attrs){
                $data['pattrs']  .=";".$attrs;
            }
            
            $data['pattrs']  = substr($data['pattrs'] ,1);
        }
    
        //请求部分
        http_web($this->api_url['store'])->send($data);
        //跳转至列表页，如果有详情页，跳转至详情页
        return redirect()->route('product.index');
    }

    public function show($id)
    {
        //请求详情
        //$product = http_web($this->api_url['show'], [$id])->send();
        dd($id);
    }

    public function edit($id)
    {
        $this->shop_id = session('user_shop_id');
        //请求详情
        $product = http_web($this->api_url['show'], [$id])->send();
        $data = [];
        if(isset($product['data']) && $product['data'] ){
            $data = $product['data'];
        }
       
        $cats = $this->request->get('cats','');
        if($cats){
            $cids= explode(",",$cats);
            if( isset($cids[0])){
                $data['first_cat'] = $cids[0];
            }
           
            if(isset($cids[1])){
                $data['second_cat'] =$cids[1];
            }
            
            if(isset($cids[2])){
                $data['third_cat'] =$cids[2];
            }
        }
        
       
        
        $params['search']=search_params(['is_sku'=>1]);
        $params['with']='attrValues';
        $params = [
            'search' => search_params(['id'=>$data['third_cat']]),
        ];
        $cates =  http_web($this->api_url['cate_index'])->send($params);
 
        $data['attrs'] = "";
        if(isset($cates['code']) && $cates['code'] === 0 ){
            if(isset($cates['data']['list'][0])){
                $data['attrs']  = json_decode($cates['data']['list'][0]['attrs'],true);
            }
        }
        $attrs_ids = [];
        if($data['product_type'] == 1){
            
//             $params = [
//                 'type' => 'all',
//             ];
            
//             $brands = http_web($this->api_url['brand_index'])->send($params);
            
//             $data['brands'] = [];
//             if(isset($brands['code']) && $brands['code'] === 0 ){
//                 $data['brands'] = $brands['data']['list'];
//             }
            
            $data['brands'] = [];
            if(Redis::exists('brand')){
                $brands  = Redis::hgetall('brand');
                foreach($brands as $b){
                    $data['brands'][] = json_decode($b,true);
                }
            }else{
                $params = [
                    'type' => 'all',
                ];
                
                $brands = http_web($this->api_url['brand_index'])->send($params);
                
                
                if(isset($brands['code']) && $brands['code'] === 0 ){
                    $data['brands'] = $brands['data']['list'];
                    foreach($brands['data']['list'] as $bl){
                        Redis::hset('brand',$bl['id'],json_encode($bl));
                    }
                }
            }
            
     
            foreach($data['skus'] as $sku){
                if($sku['attributes']){
                    $sarrs = explode(";",$sku['attributes']);
                    
                    foreach($sarrs as $sa){
                        $arrs = explode(",",$sa);
                        if ( isset($arrs[1]) ){
                            $attrs_ids[] = $arrs[1];
                            $tmp0 = explode(":",$arrs[0]);
                            $tmp1 = explode(":",$arrs[1]);
                            if(isset($data['attrs'][$tmp0[0]]['values'])){
                                $data['attrs'][$tmp0[0]]['values'][$tmp1[0]] = $tmp1[1];
                            }
                        }
                    }
                }
            }
            
            $data['attr_ids'] = json_encode(array_unique($attrs_ids));
            if(isset($data['skus']) && $data['skus']){
                $data['skus'] = json_encode($data['skus']);
            } 
        }else{
            $data['pattrs'] = "";
            if(isset($data['product_attrs']) && is_array($data['product_attrs'])){
                foreach($data['product_attrs'] as $attrs){
                    $data['pattrs']  .=";".$attrs;
                }
                
                $data['pattrs']  = substr($data['pattrs'] ,1);
            }
            
            //请求部分
            $attrs_data = http_web($this->api_url['pattrs'], [$id])->send();
         
            if(isset($attrs_data['data']['attributes'])){
                $data['attr_ids'] = json_encode(explode(";",$attrs_data['data']['attributes']));
            }
            
            if(isset($attrs_data['data']['price'])){
                $data['price'] = $attrs_data['data']['price'];
            }
        }
   
        $categories = http_web($this->api_url['categories'],[$this->shop_id])->send();
       
        $data['categories'] = [];
        if(isset($categories['data'][0])){
            $data['categories']=$categories['data'];
        }
        
        $params = [
            'search' => search_params(['id'=>$data['first_cat'].",".$data['second_cat'].",".$data['third_cat']]),
        ];
        $cates =  http_web($this->api_url['cate_index'])->send($params);
        if(isset($cates['code']) && $cates['code']===0){
            foreach($cates['data']['list'] as $cate){
                if($cate['id'] == $data['first_cat']){
                    $data['c1'] = $cate['name'];
                }
                if($cate['id'] == $data['second_cat']){
                    $data['c2'] = $cate['name'];
                }
                if($cate['id'] == $data['third_cat']){
                    $data['c3'] = $cate['name'];
                }
            }
        }
  
        
        $cupboards = http_web($this->api_url['cupboards'])->send(['shop_id'=>$this->shop_id,'product_type'=>$data['product_type']]);
        if(isset($cupboards['data'])){
            $data['cupboards'] = $cupboards['data'];
        }else{
            $data['cupboards'] = 0;
        }


        //form old塞值
        old_set($data);
        
        if($data['product_type'] == 1){
            return view('web.user.seller.product_add_detail', ['request_url' => route('product.update', $id), 'type' => 'put', $data]);
        }else{
            return view('web.user.seller.product_add_detail_zz', ['request_url' => route('product.update', $id), 'type' => 'put', $data]);
        }
        
    }
    
    public function attrval(){
        $data['value'] = $this->request->input('value','');
        $data['attribute_id'] = $this->request->input('attribute_id',0);
        $data['sort'] = 0;
        $data['shop_id'] = session('user_shop_id');
        $data['is_common'] = 0;
        $data['remark'] = session("user_name");
       
        $ret = http_web($this->api_url['attr_val_store'])->send($data);
        $resp=['status'=>0,'data'=>[]];
        if(isset($ret['data'])){
            $resp['status'] = 1;
            $resp['data'] = $ret['data'];
        }
        return response()->json($resp);
        
    }
    
    public function attrdel($id){
        //请求部分
        $ret = http_web($this->api_url['attr_val_del'],[$id])->send();
        $resp=['status'=>0,'msg'=>''];
        if($ret){
            $resp['status'] = 1;
            $resp['msg'] = '删除成功';
        }
        return response()->json($resp);
    }
    
    public function batchdel(){
        $data = $this->request->all(['ids']);
        //请求部分
        $ret = http_web($this->api_url['batchdel'])->send($data);
        return $ret;
    }
    
    public function batchsale(){
        $data = $this->request->all(['ids','is_sale']);
        //请求部分
        $ret = http_web($this->api_url['batchsale'])->send($data);
        return $ret;
    }
    
    public function update($id)
    {
        //验证部分
        $data = $this->form();
        if(isset($data['images'])){
            $data['images'] = json_encode($data['images']);
        }
        
        if(!isset($data['is_cupboard']) || !$data['is_cupboard']){
            $data['is_cupboard'] = 0;
        }
        
        //$data['name'] = $data['product_desc'];
        
        $data['pattrs'] = "";
        if(isset($data['product_attrs']) && is_array($data['product_attrs'])){
            foreach($data['product_attrs'] as $attrs){
                $data['pattrs']  .=";".$attrs;
            }
            
            $data['pattrs']  = substr($data['pattrs'] ,1);
        }

         //请求部分
        $update = http_web($this->api_url['update'], [$id])->send($data);

        Redis::del('product_show_data_'.$id);
        Redis::del('product_brand_data_'.$data['brand_id']);
        //结果处理部分
        return $update;
//        return redirect()->route('product.index');
    }
    
    
    private function form()
    {
        $cate_type = $this->request->get("cate_type",1);
      
        if($cate_type ==1){
            $this->validate($this->request, [
                'name' => 'required|string',
                'brand_id'=> 'required|integer',
                'first_cat'=> 'required|integer',
                'second_cat'=> 'required|integer',
                'third_cat'=> 'required|integer',
                'model'=>'required|string',
                'product_detail'=>'required|string',
                'place_origin'=>'required|string',
                'product_desc'=>'required|string',
                'unit'=> 'required|integer',
                'delivery_time'=>'required|integer',
                'guarantee_period'=>'required|string',
                'is_onsales'=>'required|integer',
                'is_recommend'=>'required|integer',
                'is_hot'=>'required|integer',
                'cover_image'=>'required|string',
                'images'=>'required|array',
                'skus'=>'required|string',
                'is_for_sale'=>'required|integer',
                'is_cupboard'=>'integer',
            ]);
       
        }else{
            $this->validate($this->request, [
                'product_desc' => 'required|string',
                'first_cat'=> 'required|integer',
                'second_cat'=> 'required|integer',
                'third_cat'=> 'required|integer',
                'product_detail'=>'required|string',
                'cover_image'=>'required|string',
                'images'=>'required|array',
                'is_cupboard'=>'integer',
                'price'=>'required|string',
                'place_origin'=>'required|string',
                'product_attrs'=>'required|array',
            ]);
           
        }
        
        return $this->request->all(
            ['name', 'brand_id', 'first_cat', 'second_cat','third_cat','model','skus','is_for_sale','after_sale_guarantee','product_attrs',
                'product_detail','place_origin','product_desc', 'unit', 'delivery_time','images','is_cupboard','custom_cate','price',
                'guarantee_period', 'is_onsales','is_recommend', 'is_hot','cover_image','keywords','cate_type','custom_attrs',
                
            ]);
    
    }
}